<template>
  <view class="dropdown-box">
    <ve-dropdown ref="dropdownRef" titleSize="24" @close="onDropdownClose">
      <ve-dropdown-item v-model:value="screenTypes.feeType" title="费用类型" :options="dropDownList.orderFeeTypeEnum" @change="onChange" />
      <ve-dropdown-item v-model:value="screenTypes.costType" title="收支类型" :options="dropDownList.costTypeList" @change="onChange" />
      <ve-dropdown-item v-model:value="screenTypes.feeStatus" title="结算状态" :options="dropDownList.feeStatusEnum" @change="onChange" />
    </ve-dropdown>

    <view
      class="reset"
      :class="screenTypes.feeType != null || screenTypes.costType != null || screenTypes.feeStatus != null ? 'reset-text' : ''"
      @click="onReset"
    >
      <ve-line color="#DADBDD" direction="col" length="44" margin="0rpx 24rpx 0rpx 0rpx" />
      <text>重置</text>
    </view>
  </view>

  <view class="detail-container">
    <ve-card title="费用信息" type="none" fold v-model:initFold="initExpand">
      <template #operator-left>
        <view class="all-amount c1 fs32 fw600">{{ fee.totalAmount }}元</view>
      </template>
      <ve-cell-price label="实收金额" :value="fee.receivedAmount"></ve-cell-price>
      <ve-cell-price label="待收金额" :value="fee.receivedNotAmount"></ve-cell-price>
      <ve-cell-price label="实付金额" :value="fee.payAmount"></ve-cell-price>
      <ve-cell-price label="待付金额" :value="fee.payNotAmount"></ve-cell-price>
      <ve-cell>
        <template #label>
          <ve-tooltip>
            <template #content>
              <view>为订单产生的运营支出总额</view>
            </template>
            <view>
              运营支出
              <ve-icon style="vertical-align: -4rpx" name="help" size="32" />
            </view>
          </ve-tooltip>
        </template>
        {{ fee.operateCost == null ? '-' : numFormatThousands(fee.operateCost, 1) + '元' }}
      </ve-cell>
      <ve-cell>
        <template #label>
          <ve-tooltip>
            <template #content>
              <view>订单利润=费用金额-运营支出</view>
            </template>
            <view>
              订单利润
              <ve-icon style="vertical-align: -4rpx" name="help" size="32" />
            </view>
          </ve-tooltip>
        </template>
        {{ fee.orderProfit == null ? '-' : numFormatThousands(fee.orderProfit, 1) + '元' }}
      </ve-cell>
      <view class="form-block" v-if="totalDetailList.length">
        <template v-for="(item, index) in totalDetailList" :key="index">
          <ve-cell-price :label="item.name + '账单计划总额'" :value="item.amount"></ve-cell-price>
          <ve-cell-price :label="item.name + '账单计划待收金额'" :value="item.receivedNotAmount"></ve-cell-price>
        </template>
      </view>
      <ve-gap size="24"></ve-gap>
    </ve-card>
    <!-- 费用记录 -->
    <view class="fee-card" v-for="item in orderFeeList" :key="`${orderFeeNodeKeyIndex}${item.id}`">
      <view class="title">
        <view class="status">
          <view class="status-1" v-if="item.feeStatusName">{{ item.feeStatusName }}</view>
          <view class="status-2" v-if="item.feeTypeName">{{ item.feeTypeName }}</view>
          <view class="status-3" v-if="item.costTypeName">{{ item.costTypeName }}</view>
          <view class="status-4 text-o" v-if="item.payTypeName">{{ item.payTypeName }}</view>
        </view>
      </view>
      <block v-if="item.tableOpen == false">
        <!-- 费用表格 -->
        <FeeTable :data="item" />
        <ve-cell-val label="收付款时间" :value="item.payTime || '-'" />
        <view class="table-buttons">
          <!-- feeStatus 1未收款 2已收款 3未付款  4已付款 5已驳回 9已作废 -->
          <ve-button
            type="plain"
            size="mini"
            status="gray"
            @click="feeEdit(item)"
            v-if="
              item.createNode != 0 &&
              (item.feeStatus == 5 || item.feeStatus == 3 || item.feeStatus == 1) &&
              item.feeNameId != 55 &&
              item.feeNameId != 551 &&
              item.canModify == 1
            "
          >
            修改费用
          </ve-button>
          <ve-button
            type="primary"
            size="mini"
            style="margin-left: 16rpx"
            @click="feeConfirm(item)"
            v-if="
              item.feeType == 1 &&
              (item.refId == null || !(item.feeNameId == 7 && item.refId != null)) &&
              (item.feeStatus == 5 || item.feeStatus == 1 || item.feeStatus == 3) &&
              item.feeNameId != 55 &&
              item.feeNameId != 551
            "
          >
            <text v-if="item.costType == 10">确认收款</text>
            <text v-if="item.costType == 20">确认付款</text>
          </ve-button>
          <!-- 违章费用相关操作 -->
          <ve-button
            type="plain"
            size="mini"
            status="gray"
            @click="feeEdit(item)"
            v-if="(item.feeNameId == 55 || item.feeNameId == 551) && item.canModify == 1"
          >
            修改费用
          </ve-button>
          <ve-button type="primary" size="mini" style="margin-left: 16rpx" @click="feeConfirm(item)" v-if="item.ifCanConfirm">
            <text v-if="item.costType == 0">确认收款</text>
            <text v-if="item.costType == 1">确认付款</text>
          </ve-button>

          <ve-button
            type="plain"
            status="gray"
            size="mini"
            v-if="item.feeStatus == 6 && usePermission('svmsapp:order:long-order.qrcodeCancel')"
            style="margin-left: 16rpx"
            @click="onClickQRCode('order/long-order/detail/index_cancel', item)"
          >
            取消收款
          </ve-button>
          <ve-button
            type="primary"
            size="mini"
            @click="onClickQRCode('order/long-order/detail/index', item)"
            v-if="item.feeStatus == 6 && usePermission('svmsapp:order:long-order.qrcode')"
            style="margin-left: 16rpx"
          >
            收款码
          </ve-button>
        </view>
      </block>
    </view>
  </view>

  <ve-bottom-box>
    <ve-button type="primary" @click="mergeConfirm" size="long">合并确认</ve-button>
  </ve-bottom-box>
</template>

<script setup lang="ts">
  import FeeTable from './fee-table.vue'

  import { getOrdrFeeDetailAPI } from '@/api/order/lOrder'
  import { costScreenOrder } from '@/api/order/sOrder'
  import { usePermission } from '@/hooks/usePermission'
  import { decimalSubtract } from '@/utils'
  import { numFormatThousands } from '@/vehicle-ui/utils/tools.js'

  import { ref, reactive } from 'vue'
  import { onLoad, onShow } from '@dcloudio/uni-app'

  const props = defineProps({
    orderId: {
      type: String || Number,
      default: '',
    },
  })

  //筛选参数
  const screenTypes = reactive({
    feeType: null,
    costType: null,
    feeStatus: null,
  })

  const initExpand = ref(true)
  const fee = ref<any>({})
  const totalDetailList = ref<any>({})
  const orderFeeList = ref<any>([])

  // 记录一个自增的“orderFeeNodeKeyIndex”，解决onShow后列表更新，数据不变问题
  const orderFeeNodeKeyIndex = ref(0)
  const getDetail = (id: string | number) => {
    return new Promise((resolve) => {
      getOrdrFeeDetailAPI({ id }).then((res) => {
        orderFeeNodeKeyIndex.value += 1
        const datafee: any = res.result
        fee.value = datafee

        var dataOne: any[] = []
        var dataTwo: any[] = []

        // 筛选dataOne和dataTwo
        if (fee.value.orderFeeList && fee.value.orderFeeList.length) {
          fee.value.orderFeeList.forEach((i: any) => {
            if (
              (screenTypes.feeType == null || screenTypes.feeType == i.feeType) &&
              (screenTypes.costType == null || screenTypes.costType == i.costType) &&
              (screenTypes.feeStatus == null || screenTypes.feeStatus == i.feeStatus)
            ) {
              dataOne.push(i)
            }
          })
        }
        if (fee.value.violationFeeList && fee.value.violationFeeList.length) {
          fee.value.violationFeeList.forEach((i: any) => {
            // costType转换changeCostType 匹配订单费
            if (i.costType == 0) {
              i.changeCostType = 10
            }
            if (i.costType == 1) {
              i.changeCostType = 20
            }
            // feeStatus转换changeFeeStatus 匹配订单费
            if (i.feeStatus == 0) {
              i.changeFeeStatus = 3
            }
            if (i.feeStatus == 1) {
              i.changeFeeStatus = 4
            }
            if (i.feeStatus == 2) {
              i.changeFeeStatus = 2
            }
            if (i.feeStatus == 3) {
              i.changeFeeStatus = 1
            }
            if (i.feeStatus == 5) {
              i.changeFeeStatus = 5
            }
            if (i.feeStatus == 9) {
              i.changeFeeStatus = 9
            }
            // 违章费筛选匹配
            if (
              (screenTypes.feeType == null || screenTypes.feeType == i.feeType) &&
              (screenTypes.costType == null || screenTypes.costType == i.changeCostType) &&
              (screenTypes.feeStatus == null || screenTypes.feeStatus == i.changeFeeStatus)
            ) {
              dataTwo.push(i)
            }
          })
        }

        const violationFeeList = (dataTwo || []).map((item) => {
          item.activeTotalAmount = item.totalAmount
          item.waitPayAmount = item.outstandingAmount //待结金额
          item.tableOpen = false //控制单个费用 整个表的显示隐藏
          item.open = false //控制1级
          if (item.feeDetailList) {
            item.feeDetailList.forEach((el: any) => {
              el.feeName = el.itemName
              el.activeAmount = el.amount
              if (!el.childrenList) {
                el.childrenList = []
              }
            })
          }
          return item
        })

        const orderFeeList1 = (dataOne || []).map((item) => {
          item.tableOpen = false //控制单个费用 整个表的显示隐藏
          item.open = false //控制1级
          item.waitPayAmount = decimalSubtract(item.totalAmount, item.payAmount)
          return item
        })

        orderFeeList.value = [...orderFeeList1, ...violationFeeList]
        totalDetailList.value = datafee.totalDetailList || []

        resolve([...orderFeeList1, ...violationFeeList])
      })
    })
  }

  const loadData = () => {
    getDetail(props.orderId).then((data: any) => {
      console.log('data', data)
    })
  }

  // 获取筛选条件
  const dropDownList = reactive({
    orderFeeTypeEnum: [],
    costTypeList: [],
    feeStatusEnum: [],
  })
  const getScreen = () => {
    costScreenOrder({}).then((res: any) => {
      const { result } = res

      for (const key in result) {
        if (Object.prototype.hasOwnProperty.call(result, key)) {
          const element = result[key]
          element.map((item: any) => {
            item.label = item.name
          })
        }
      }

      dropDownList.orderFeeTypeEnum = result.orderFeeTypeEnum
      dropDownList.costTypeList = result.costTypeEnum
      dropDownList.feeStatusEnum = result.orderFeeStatusEnum
    })
  }

  // 合并确认
  const mergeConfirm = () => {
    uni.navigateTo({
      url: '/pages/order/long-order/detail/mergeConfirmation?orderId=' + props.orderId,
    })
  }
  // 单个确认
  const feeConfirm = (record: any) => {
    if (record.feeCategory && (record.feeCategory == 4 || record.feeCategory == 41)) {
      uni.navigateTo({
        url: `/pages/asset/asset-fee/confirm-fee?id=${record.id}&feeCategory=4&orderId=${record.orderId}&orderType=3&feeNameId=${record.feeNameId}`,
      })
    } else {
      uni.navigateTo({
        url: `/pages/order/long-order/detail/confirmExpenses?idList=${JSON.stringify([record.id])}&pagefrom=expense`,
      })
    }
  }

  // 修改费用
  const feeEdit = (feeItem: any) => {
    // 存在分期方式，并且分期方式为 分期
    if (feeItem.feeCategory && (feeItem.feeCategory == 4 || feeItem.feeCategory == 41)) {
      uni.navigateTo({
        url: `/pages/asset/asset-fee/edit-fee?id=${feeItem.id}&feeCategory=4&addorEdit=1&businesId=${feeItem.id}&feeNameId=${feeItem.feeNameId}`,
      })
    } else if (feeItem.paymentWay && feeItem.paymentWay != 1) {
      uni.navigateTo({
        url: '/pages/order/long-order/edit-stages-fees?id=' + feeItem.id,
      })
    } else {
      uni.navigateTo({
        url: '/pages/order/long-order/edit-fees?id=' + feeItem.id,
      })
    }
  }

  const dropdownRef = ref()
  const indexList = ref<number[]>([])

  // 获取当前筛选条件是否有值
  const getScreenValue = (index: number) => {
    switch (index) {
      case 0:
        return screenTypes.feeType != null
      case 1:
        return screenTypes.costType != null
      case 2:
        return screenTypes.feeStatus != null
      default:
        break
    }
  }

  const onChange = () => {
    loadData()
  }

  const onReset = () => {
    if (screenTypes.feeType == null && screenTypes.costType == null && screenTypes.feeStatus == null) {
      return
    }

    screenTypes.feeType = null
    screenTypes.costType = null
    screenTypes.feeStatus = null
    indexList.value = []
    dropdownRef.value.highlight([])
    loadData()
  }

  const onDropdownClose = (index: number) => {
    if (index != 99999 && getScreenValue(index)) {
      if (!indexList.value.includes(index)) {
        indexList.value.push(index)
      }

      dropdownRef.value.highlight(indexList.value)
    }
  }

  onLoad(() => {
    getScreen()
  })

  const onClickQRCode = (from: any, record: any) => {
    console.log('long onClickQRCode', record)

    const bizType = record.feeNameId == 55 || record.feeNameId == 551 ? 3 : 2
    const refId = record.feeNameId == 55 || record.feeNameId == 551 ? record.businesId : record.orderId

    uni.navigateTo({
      url: `/pages/common/components/qrcode?id=${record.id}&refId=${refId}&bizType=${bizType}&from=${from}`,
    })
  }

  onShow(() => {
    if (props.orderId) {
      loadData()
    }
  })
</script>

<style lang="scss" scoped>
  .dropdown-box {
    position: -webkit-sticky;
    position: sticky;
    // #ifdef APP-PLUS
    top: 0px;
    // #endif
    // #ifdef H5
    top: 44px;
    // #endif
    height: 80rpx;
    background-color: #fff;
    z-index: 1;

    :deep(.ve-dropdown) {
      padding: 0 12px;

      .ve-dropdown__menu__item {
        flex: none;
        justify-content: flex-start;
        margin-right: 15px;
      }
    }

    .reset {
      position: absolute;
      right: 12px;
      top: 0;
      bottom: 0;
      margin: auto;

      display: flex;
      align-items: center;
      font-weight: 400;
      font-size: 12px;
      color: #dadfe8;
      z-index: 12;
      image {
        width: 12px;
        height: 12px;
        margin-right: 5px;
      }
    }
    .reset-text {
      color: #3072f6;
    }
  }

  .detail-container {
    padding: 40rpx 24rpx 24rpx;
  }
  .upinfo {
    padding: 24rpx;
  }
  .all-amount {
    margin-right: 20rpx;
    text-align: right;
  }
  .fee-card {
    background: #ffffff;
    border-radius: 8rpx;
    padding: 0 24rpx 24rpx;
    margin-bottom: 24rpx;
    .title {
      padding: 20rpx 0;
      border-bottom: 1px solid rgba(216, 216, 216, 0.3);
      .status {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        .status-1 {
          background: #ffece8;
          color: #f53f3f;
          border: 2rpx solid #f53f3f;
          border-radius: 450rpx;
          padding: 0 16rpx;
          height: 40rpx;
          line-height: 40rpx;
          font-size: 24rpx;
          margin-right: 10rpx;
        }
        .status-2 {
          background: #e8f7ff;
          color: #3491fa;
          border: 2rpx solid #3491fa;
          border-radius: 450rpx;
          padding: 0 16rpx;
          height: 40rpx;
          line-height: 40rpx;
          font-size: 24rpx;
          margin-right: 10rpx;
        }
        .status-3 {
          background: #fff7e8;
          color: #ff7d00;
          border: 2rpx solid #ff7d00;
          border-radius: 450rpx;
          padding: 0 16rpx;
          height: 40rpx;
          line-height: 40rpx;
          font-size: 24rpx;
          margin-right: 10rpx;
        }
        .status-4 {
          background: #f5e8ff;
          color: #722ed1;
          border: 2rpx solid #722ed1;
          border-radius: 450rpx;
          padding: 0 16rpx;
          height: 40rpx;
          line-height: 40rpx;
          font-size: 24rpx;
          margin-right: 10rpx;
          // 文字超长
          display: inline-block;
          max-width: 280rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      .open-close {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        text {
          color: rgba(48, 114, 246, 1);
          margin-right: 4rpx;
          font-size: 28rpx;
        }
      }
    }

    .table-buttons {
      border-top: 1px solid rgba(216, 216, 216, 0.3);
      margin-top: 24rpx;
      // padding-top: 24rpx;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      .time {
        color: #191c27;
        font-size: 28rpx;
      }
      .ve-button {
        margin-top: 24rpx;
      }
    }
  }
</style>
